import WidgetKit
import SwiftUI

struct UsCartoonEntry: TimelineEntry {
    let date: Date
    let daysTogether: Int
    let nickname1: String
    let nickname2: String
    let image1: UIImage?
    let image2: UIImage?
}

struct UsCartoonProvider: TimelineProvider {
    func placeholder(in context: Context) -> UsCartoonEntry {
        UsCartoonEntry(date: Date(), daysTogether: 120, nickname1: "yoni", nickname2: "momo", image1: nil, image2: nil)
    }

    func getSnapshot(in context: Context, completion: @escaping (UsCartoonEntry) -> Void) {
        completion(UsCartoonEntry(date: Date(), daysTogether: 120, nickname1: "yoni", nickname2: "momo", image1: nil, image2: nil))
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<UsCartoonEntry>) -> Void) {
        let defaults = UserDefaults(suiteName: "group.emmo.us")
        let nickname1 = defaults?.string(forKey: "nickname1") ?? ""
        let nickname2 = defaults?.string(forKey: "nickname2") ?? ""
        let timestamp = defaults?.double(forKey: "startTime") ?? 0
        let startDate = Date(timeIntervalSince1970: timestamp)
        let days = calculateDaysSince(start: startDate)
        let image1 = loadImage(named: "my.png")
        let image2 = loadImage(named: "rel.png")
        let entry = UsCartoonEntry(date: Date(), daysTogether: days, nickname1: nickname1, nickname2: nickname2, image1: image1, image2: image2)
        let timeline = Timeline(entries: [entry], policy: .atEnd)
        completion(timeline)
    }

    private func calculateDaysSince(start: Date) -> Int {
        let current = Calendar.current.startOfDay(for: Date())
        let start = Calendar.current.startOfDay(for: start)
        return Calendar.current.dateComponents([.day], from: start, to: current).day ?? 0
    }

    private func loadImage(named fileName: String) -> UIImage? {
        guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.emmo.us") else { return nil }
        let fileURL = containerURL.appendingPathComponent(fileName)
        guard let data = try? Data(contentsOf: fileURL) else { return nil }
        return UIImage(data: data)
    }
}

struct UsCartoonWidgetEntryView: View {
    var entry: UsCartoonEntry

    var body: some View {
        
        VStack(spacing: 4) {
            Text("\(entry.nickname1) ❤️ \(entry.nickname2)")
                .font(.system(size: 12, weight: .regular))
                .foregroundColor(.black)
                .minimumScaleFactor(0.5)

            (
                Text("D+")
                    .foregroundColor(.black) +
                Text("\(entry.daysTogether)")
                    .foregroundColor(Color("usRedColor"))
            ).minimumScaleFactor(0.5)
            .font(.system(size: 20, weight: .medium, design: .rounded))

            if let img1 = entry.image1, let img2 = entry.image2 {
                
                HStack(spacing: -30) {
                    Image(uiImage: img1)
                        .resizable()
                        .frame(width: 80,height: 80)
                    Image(uiImage: img2)
                        .resizable()
                        .frame(width: 80,height: 80)
                        
                }
                .frame(height: 80)
                
            } else {
                
                Image("ic_header")
                    .resizable()
                    .scaledToFit()
            }
            
        }

    }
    
}

struct UsCartoonWidget: Widget {
    
    let kind: String = "UsCartoonWidget"
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: UsCartoonProvider()) { entry in
            UsCartoonWidgetEntryView(entry: entry)
                .containerBackground(Color("usBackgroundColor"), for: .widget)
        }
        .contentMarginsDisabled()
        .configurationDisplayName("我们在一起")
        .description("展示你们的名字、天数和头像")
        .supportedFamilies([.systemSmall])
    }
}
